<?php
class MenuService extends BaseDbService
{
	public function __construct()
	{
		$this->dao	= new MenuDao();
	}
	
	public function get($id)
	{
		$tmp	= $this->getList();
		if(!$tmp || count($tmp)<$id)
		{
			return false;
		}
		return $tmp[$id-1];
	}
	
	public function add($data)
	{
		$tmp		= $this->getList();
		if(!$tmp)
		{
			$tmp	= array();
		}
		$tmp[]		= $data;
		$this->updateData($tmp);
	}
	
	public function update($id,$data)
	{
		$tmp	= $this->getList();
		if($tmp && count($tmp)>=$id)
		{
			foreach($data as $k=>$v)
			{
				$tmp[$id-1][$k]	= $v;
			}
			$this->updateData($tmp);
		}
	}
	
	public function del($id)
	{
		$tmp	= $this->getList();
		if($tmp && count($tmp)>=$id)
		{
			unset($tmp[$id-1]);
			$this->updateData($tmp);
		}
	}
	
	private function updateData($data)
	{
		$this->dao->update($data);
		
		$this->updateCache();
	}
	
	private function updateCache()
	{
		$list	= $this->dao->getList();
		
		$cache 	= new LtCache();
		$cache->init();
		$ch 	= $cache->getTDG(C('LtConfig')->get('db.table.prefix')."menu");
		$tmp	= $ch->get('menu_list');
		if($tmp!==false)
		{
			$ch->update('menu_list',$list);
		}
		else
		{
			$ch->add('menu_list',$list);
		}
	}
	
	public function getList($cache=true)
	{
		if($cache)
		{
			$cache 	= new LtCache();
			$cache->init();
			$ch 	= $cache->getTDG(C('LtConfig')->get('db.table.prefix')."menu");
			$tmp	= $ch->get('menu_list');
			if($tmp)
			{
				return $tmp;
			}
		}
		$tmp	= $this->dao->getList();
		if($cache && $tmp)
		{
			$this->updateCache();
		}
		return $tmp;
	}
}